package com.glq1218.controller;

import com.glq1218.enums.ResultEnum;
import com.glq1218.response.ResponseResult;
import com.glq1218.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.Random;


@RestController
public class VerificationCodeController {
    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("/verificationCode")
    public ResponseResult<String> sendVerificationCode(Integer type, String account, String captcha) {
        if (!StringUtils.hasText(account)) {
            return ResponseResult.error("账号不能为空");
        }
        if (!StringUtils.hasText(captcha)) {
            return ResponseResult.error("图片验证码不能为空");
        }
        if (Objects.equals(captcha, redisUtils.get("captcha:" + account))) {
            String code = creatCode(5);
            switch (type) {
                case 1: {
                    redisUtils.set("verificationCode:phone:" + account, code, 60);
                    break;
                }
                case 2: {
                    redisUtils.set("verificationCode:email:" + account, code, 60);
                    break;
                }
                default: {
                    return ResponseResult.error(ResultEnum.NO_LOGIN_TYPE);
                }
            }
            return ResponseResult.success(code, "验证码为：" + code + "，60秒有效时间");
        }
        return ResponseResult.error("图片验证码错误");
    }

    //定义一个方法返回一个随机验证码
    public static String creatCode(int n) {

        //定义一个字符串变量 记录生成的随机数
        String code = "";
        Random r = new Random();


        //2.在方法内部使用for循环生成指定位数的随机字符，并连接起来
        for (int i = 0; i <= n; i++) {
            //生成一个随机字符：大写 ，小写 ，数字（0  1  2）
            int type = r.nextInt(3);
            switch (type) {
                //大写字母  65   ~   65+25
                case 0:
                    char ch = (char) (r.nextInt(26) + 65);
                    code += ch;
                    break;
                //小写字母  90   ~   97+25
                case 1:
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                //大写字母  65   ~   65+25
                case 2:
                    code += r.nextInt(10);
                    break;
            }

        }
        return code;
    }
}
